AuthInterceptor.setAuthorizationHeader   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 13
rs 10
c 0
b 0
f 0
cc 3
1
import { AxiosRequestConfig } from 'axios';
2
import { GrantType } from '../bedita-api-client';
3
import RequestInterceptor from './request-interceptor';
4
5
/**
6
 * Auth interceptor.
7
 * It responsible to add Authorization header if it needs.
8
 */
9
export default class AuthInterceptor extends RequestInterceptor {
10
11
    /**
12
     * If present it adds access token to Authorization header.
13
     *
14
     * @param config The axios request config
15
     */
16
    public async requestHandler(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {
17
        config = await this.setAuthorizationHeader(config);
18
19
        // Authorization header set so go ahead
20
        if (config.headers?.Authorization) {
21
            return config;
22
        }
23
24
        // trying client credentials auth so go ahead
25
        if (config.url === '/auth' && config.data?.grant_type === GrantType.ClientCredentials) {
26
            return config;
27
        }
28
29
        if (!this.beditaClient.getConfig('clientId')) {
30
            return config;
31
        }
32
33
        await this.beditaClient.clientCredentials();
34
35
        return await this.setAuthorizationHeader(config);
36
    }
37
38
    /**
39
     * Set Authorization header if not already set and access token is present.
40
     *
41
     * @param config The axios request config
42
     */
43
    protected async setAuthorizationHeader(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {
44
        const accessToken = await this.beditaClient.getStorageService().getAccessToken();
45
        if (accessToken && !config.headers?.Authorization) {
46
            config.headers.Authorization = `Bearer ${accessToken}`;
47
        }
48
49
        return config;
50
    }
51
}
52